package com.lfs.market.service.impl;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.code.kaptcha.Constants;
import com.lfs.market.constants.RedisConstant;
import com.lfs.market.exception.ServiceException;
import com.lfs.market.mapper.SystemUserMapper;
import com.lfs.market.model.R;
import com.lfs.market.model.dto.SystemUserCreateDto;
import com.lfs.market.model.dto.SystemUserLoginDto;
import com.lfs.market.model.dto.SystemUserPageDto;
import com.lfs.market.model.dto.SystemUserUpdateDto;
import com.lfs.market.model.entity.SystemRole;
import com.lfs.market.model.entity.SystemUser;
import com.lfs.market.model.enums.ResultCode;
import com.lfs.market.service.SystemRoleService;
import com.lfs.market.service.SystemUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Locale;


@Service
public class SystemUserServiceImpl extends ServiceImpl<SystemUserMapper, SystemUser> implements SystemUserService {
    @Autowired
    private SystemRoleService systemRoleService;

    @Autowired
    private SystemUserService systemUserService;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public SaTokenInfo login(SystemUserLoginDto request) {
        if (StrUtil.isEmpty(request.getVerifyCode())) {
            throw new ServiceException(ResultCode.Fail, "验证码不能为空");
        }
        Long expire = redisTemplate.boundHashOps(RedisConstant.KAPTCHA_KEY).getExpire();
        if (expire < 0L) {
            throw new ServiceException(ResultCode.Fail, "验证码已过期");
        }

        Object kaptCha = redisTemplate.opsForValue().get(RedisConstant.KAPTCHA_KEY);
        if (!request.getVerifyCode().toLowerCase().equals(kaptCha.toString().toLowerCase())) {
            throw new ServiceException(ResultCode.Fail, "验证码错误");
        }
        SystemUser systemUser = lambdaQuery().eq(SystemUser::getUsername, request.getUsername()).one();
        if (null == systemUser) {
            throw new ServiceException(ResultCode.NotFindError);
        }
        String password = systemUser.getPassword();
        String md5 = SaSecureUtil.md5(request.getPassword());
        if (!md5.equals(password)) throw new ServiceException(ResultCode.Fail, "账户名或密码错误");
        systemUser.setUpdateTime(new Date());
        updateById(systemUser);
        StpUtil.login(systemUser.getId());
        return StpUtil.getTokenInfo();
    }

    /**
     * 后台注册，注册即为超级管理员
     *
     * @param request
     * @return
     */
    @Override
    public SaTokenInfo register(SystemUserLoginDto request) {
        if (StrUtil.isEmpty(request.getVerifyCode())) {
            throw new ServiceException(ResultCode.Fail, "验证码不能为空");
        }
        Long expire = redisTemplate.boundHashOps(RedisConstant.KAPTCHA_KEY).getExpire();
        if (expire < 0L) {
            throw new ServiceException(ResultCode.Fail, "验证码已过期");
        }

        Object kaptCha = redisTemplate.opsForValue().get(RedisConstant.KAPTCHA_KEY);
        if (!request.getVerifyCode().toLowerCase().equals(kaptCha.toString().toLowerCase())) {
            throw new ServiceException(ResultCode.Fail, "验证码错误");
        }

        SystemUser su = lambdaQuery().eq(SystemUser::getUsername, request.getUsername()).one();
        if (null != su) {
            throw new ServiceException(ResultCode.Fail, "用户已存在");
        }
        SystemUser systemUser = new SystemUser();
        systemUser.setUsername(request.getUsername());
        systemUser.setPassword(request.getPassword());

        SystemRole role = systemRoleService.lambdaQuery().eq(SystemRole::getRoleCode, "admin").one();
        systemUser.setRoleCode(role.getRoleCode());
        systemUser.setRoleId(role.getId());
        systemUser.setName(role.getRoleName());
        systemUser.setCreateTime(new Date());
        systemUser.setUpdateTime(new Date());

        boolean save = save(systemUser);
        if (!save) throw new ServiceException(ResultCode.Fail);
        StpUtil.login(systemUser.getId());
        return StpUtil.getTokenInfo();
    }

    @Override
    public R<SystemUser> getUserInfo() {
        Object loginId = StpUtil.getLoginId();
        SystemUser user = lambdaQuery().eq(SystemUser::getId, loginId).one();
        if (user == null) {
            throw new ServiceException(ResultCode.NotFindError, "用户不存在");
        }
        return R.ok(user);
    }

    @Override
    public Page getUserPageList(SystemUserPageDto userPageDto) {
        Page<SystemUser> page = lambdaQuery()
                .like(StrUtil.isNotEmpty(userPageDto.getKey()), SystemUser::getUsername, userPageDto.getKey()).or()
                .like(StrUtil.isNotEmpty(userPageDto.getKey()), SystemUser::getName, userPageDto.getKey())
                .orderByDesc(SystemUser::getCreateTime)
                .page(new Page<>(userPageDto.getPageNumber(), userPageDto.getPageSize()));
        return page;

    }

    @Override
    public void create(SystemUserCreateDto dto) {

/*        SystemRole role = systemRoleService.lambdaQuery().eq(SystemRole::getRoleCode, dto.getRoleCode()).one();
        if (ObjectUtil.isEmpty(role)) throw new ServiceException(ResultCode.ValidateError);
        Long count = lambdaQuery().eq(SystemUser::getUsername, dto.getUsername()).count();
        if (count > 1) throw new ServiceException(ResultCode.SaveError, "用户名存在");
        SystemUser systemUser = BeanUtil.toBean(dto, SystemUser.class);
        systemUser.setCreateTime(new Date());
        systemUser.setUpdateTime(new Date());
        systemUser.setRoleId(role.getId());
        systemUser.setRoleCode(role.getRoleCode());
        systemUser.setRoleName(role.getRoleName());
        systemUser.setPassword(SaSecureUtil.md5(dto.getPassword()));
        boolean save = save(systemUser);
        if (!save) throw new ServiceException(ResultCode.SaveError);*/
    }

/*    @Override
    public void edit(SystemUserUpdateDto dto) {
        if (StrUtil.isEmpty(dto.getId())) throw new ServiceException(ResultCode.ValidateError);
        SystemUser systemUser = getById(dto.getId());
        SystemRole role = systemRoleService.lambdaQuery().eq(SystemRole::getRoleCode, dto.getRoleCode()).one();
        systemUser.setUsername(dto.getUsername());
        systemUser.setRoleId(role.getId());
        systemUser.setRoleName(role.getRoleName());
        systemUser.setName(dto.getName());
        if (StrUtil.isNotEmpty(dto.getPassword())) {
            String md5 = SaSecureUtil.md5(dto.getPassword());
            systemUser.setPassword(md5);
        }
        systemUser.setUpdateTime(new Date());
        boolean update = updateById(systemUser);
        if (!update)
            throw new ServiceException(ResultCode.UpdateError);
    }*/

}
